var Web3 = require("web3");
var fs = require("fs");

var web3;
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
  } else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider("http://115.238.146.143:8545"));
  }

var abi = JSON.parse(fs.readFileSync("Works.json").toString());

var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at('0xea12cD4171efB697f8340B1802B0E3408B1C5648');

function Register(username, pwd) {
  
  let sealedpwd = web3.sha3(username.toString() + pwd.toString());

  var addreSS = web3.personal.newAccount(pwd);
  var a = myContractInstance.Register(addreSS, sealedpwd, {from: web3.eth.accounts[0], gas: 2000000});
  console.log(addreSS);
  return addreSS;
    
}

function Login(username, pwd) {
  let sealedpwd = web3.sha3(username.toString() + pwd.toString());
  var result = myContractInstance.Login(sealedpwd);
  console.log(result);
}

function modifyPwd(username, pwd_old, pwd_new, userAddress) {
  let sealedpwd_old = web3.sha3(username.toString() + pwd_old.toString());
  let sealedpwd_new = web3.sha3(username.toString() + pwd_new.toString());
  var result = myContractInstance.modifyPwd(sealedpwd_old, sealedpwd_new, {from: userAddress, gas: 2000000});
  console.log(result);
}

function transfer(toAddress, num) {
  let tmp = 0;
  if (toAddress.length == 0) {
    tmp = 1;
    console.log("请先注册或登录！");
  }
  if (num.toString() > "5") {
    tmp = 1;
    console.log("每次最多转账 5 Eth!");
  }
  let value1 = web3.toWei(num.toString(), 'ether');
  console.log("value: ", value1);
  if (tmp == 0) {
   web3.eth.sendTransaction({from: web3.eth.accounts[1],to:toAddress,value:value1})
   console.log("转账成功！")
  }
}

function getBalance(address) {
  return web3.fromWei(web3.eth.getBalance(address), 'ether').toString();
}

function unLock(address, password, unlock_time) {
  web3.personal.unlockAccount(address,password,unlock_time);
}

// address = Register('ming', '1999'); // 0x1eef443f8d4f2fc59281ad69166472d3017c9652
// unLock(address, '1999', 999999999);
//Login('ming', '19');

//modifyPwd('ming', '1999', '19991207', web3.eth.accounts[0]);
//Login('ming', '19991207');
console.log(getBalance(web3.eth.accounts[5]));


